/**
 * API 客户端
 * 封装所有后端 API 接口调用
 */

const API_BASE_URL = 'http://localhost:5000/api';

// API 客户端类
class ApiClient {
    constructor(baseUrl = API_BASE_URL) {
        this.baseUrl = baseUrl;
    }

    // ============ 会话相关接口 ============
    
    /**
     * 获取所有会话列表
     */
    async getConversations() {
        try {
            const response = await axios.get(`${this.baseUrl}/conversations`);
            return response.data;
        } catch (error) {
            console.error('获取会话列表失败:', error);
            if (window.ErrorHandler) {
                window.ErrorHandler.showError(error);
            }
            throw error;
        }
    }

    /**
     * 创建新会话
     * @param {string} title - 会话标题
     */
    async createConversation(title = '新对话') {
        try {
            const response = await axios.post(`${this.baseUrl}/conversations`, { title });
            return response.data;
        } catch (error) {
            console.error('创建会话失败:', error);
            throw error;
        }
    }

    /**
     * 删除会话
     * @param {number} conversationId - 会话ID
     */
    async deleteConversation(conversationId) {
        try {
            const response = await axios.delete(`${this.baseUrl}/conversations/${conversationId}`);
            return response.data;
        } catch (error) {
            console.error('删除会话失败:', error);
            if (window.ErrorHandler) {
                window.ErrorHandler.showError(error);
            }
            throw error;
        }
    }

    /**
     * 清除会话的所有消息（保留会话）
     * @param {number} conversationId - 会话ID
     */
    async clearMessages(conversationId) {
        try {
            const response = await axios.delete(`${this.baseUrl}/conversations/${conversationId}/messages`);
            return response.data;
        } catch (error) {
            console.error('清除消息失败:', error);
            if (window.ErrorHandler) {
                window.ErrorHandler.showError(error);
            }
            throw error;
        }
    }

    /**
     * 获取单个会话详情
     * @param {number} conversationId - 会话ID
     */
    async getConversation(conversationId) {
        try {
            const response = await axios.get(`${this.baseUrl}/conversations/${conversationId}`);
            return response.data;
        } catch (error) {
            console.error('获取会话详情失败:', error);
            throw error;
        }
    }

    // ============ 对话相关接口 ============
    
    /**
     * 发送消息（流式输出）
     * @param {number} conversationId - 会话ID
     * @param {string} message - 消息内容
     * @param {Function} onChunk - 接收流式数据的回调函数 (chunk) => {}
     * @param {Function} onComplete - 完成回调函数 (fullContent) => {}
     * @param {Function} onError - 错误回调函数 (error) => {}
     */
    async sendMessageStream(conversationId, message, onChunk, onComplete, onError, settings = {}, abortController) {
        try {
            const response = await fetch(`${this.baseUrl}/chat`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    conversation_id: conversationId,
                    message: message,
                    model: settings.model,
                    temperature: settings.temperature,
                    max_tokens: settings.max_tokens
                }),
                signal: abortController ? abortController.signal : undefined
            });

            if (!response.ok) {
                const errorData = await response.json();
                if (onError) onError(errorData.error || '请求失败');
                return;
            }

            const reader = response.body.getReader();
            const decoder = new TextDecoder();
            let buffer = '';
            let fullContent = '';

            while (true) {
                const { done, value } = await reader.read();
                if (done) break;

                buffer += decoder.decode(value, { stream: true });
                const lines = buffer.split('\n');
                buffer = lines.pop() || '';

                for (const line of lines) {
                    if (line.startsWith('data: ')) {
                        const data = line.slice(6);
                        if (data.trim() === '[DONE]') {
                            if (onComplete) onComplete(fullContent);
                            return;
                        }

                        try {
                            const parsed = JSON.parse(data);
                            if (parsed.error) {
                                if (onError) onError(parsed.error);
                                return;
                            }
                            if (parsed.content) {
                                fullContent += parsed.content;
                                if (onChunk) onChunk(parsed.content);
                            }
                            if (parsed.done && onComplete) {
                                onComplete(parsed.full_content || fullContent);
                            }
                        } catch (e) {
                            console.error('解析流式数据失败:', e);
                        }
                    }
                }
            }
        } catch (error) {
            console.error('发送消息失败:', error);
            if (error.name === 'AbortError') {
                // 主动停止，不当做错误提示
                if (onComplete) onComplete('');
                return;
            }
            const errorInfo = window.ErrorHandler ? window.ErrorHandler.parseError(error) : { message: error.message || '未知错误' };
            if (onError) onError(errorInfo.message);
        }
    }

    /**
     * 发送消息（兼容旧接口）
     * @param {number} conversationId - 会话ID
     * @param {string} message - 消息内容
     */
    async sendMessage(conversationId, message) {
        return new Promise((resolve, reject) => {
            let fullContent = '';
            this.sendMessageStream(
                conversationId,
                message,
                (chunk) => { fullContent += chunk; },
                (content) => {
                    resolve({
                        success: true,
                        data: { message: content, conversation_id: conversationId }
                    });
                },
                (error) => {
                    reject(new Error(error));
                }
            );
        });
    }


    // ============ 文件相关接口 ============
    
    // 已移除：文件上传与解析接口

    // ============ 图像生成接口 ============
    
    /**
     * 生成图像
     * @param {string} prompt - 图像描述
     * @param {number} conversationId - 会话ID
     */
    async generateImage(prompt, conversationId, settings = {}) {
        try {
            const response = await axios.post(`${this.baseUrl}/images/generate`, {
                prompt: prompt,
                conversation_id: conversationId,
                model: settings.model,
                size: settings.size
            });
            return response.data;
        } catch (error) {
            console.error('生成图像失败:', error);
            if (window.ErrorHandler) {
                window.ErrorHandler.showError(error);
            }
            throw error;
        }
    }

    // ============ 视频生成接口 ============
    
    /**
     * 生成视频（异步）
     * @param {string} prompt - 视频描述
     * @param {number} conversationId - 会话ID
     */
    async generateVideo(prompt, conversationId, settings = {}) {
        try {
            const response = await axios.post(`${this.baseUrl}/videos/generate`, {
                prompt: prompt,
                conversation_id: conversationId,
                model: settings.model,
                quality: settings.quality,
                with_audio: settings.with_audio,
                size: settings.size,
                fps: settings.fps
            });
            return response.data;
        } catch (error) {
            console.error('生成视频失败:', error);
            if (window.ErrorHandler) {
                window.ErrorHandler.showError(error);
            }
            throw error;
        }
    }

    /**
     * 查询异步任务状态
     * @param {string} taskId - 任务ID
     */
    async getTaskStatus(taskId) {
        try {
            const response = await axios.get(`${this.baseUrl}/tasks/${taskId}`);
            return response.data;
        } catch (error) {
            console.error('查询任务状态失败:', error);
            throw error;
        }
    }

    /**
     * 轮询查询任务状态直到完成
     * @param {string} taskId - 任务ID
     * @param {Function} onUpdate - 状态更新回调 (status, result) => {}
     * @param {number} maxAttempts - 最大查询次数
     * @param {number} interval - 查询间隔（毫秒）
     */
    async pollTaskStatus(taskId, onUpdate, maxAttempts = 30, interval = 3000) {
        let attempts = 0;
        
        const poll = async () => {
            try {
                const result = await this.getTaskStatus(taskId);
                if (result.success) {
                    const status = result.data.status;
                    if (onUpdate) onUpdate(status, result.data.result);
                    
                    if (status === 'completed' || status === 'failed') {
                        return result;
                    }
                    
                    if (attempts < maxAttempts) {
                        attempts++;
                        setTimeout(poll, interval);
                    } else {
                        throw new Error('查询超时');
                    }
                } else {
                    throw new Error(result.error || '查询失败');
                }
            } catch (error) {
                console.error('轮询任务状态失败:', error);
                if (onUpdate) onUpdate('failed', null);
                throw error;
            }
        };
        
        return poll();
    }

    // ============ 语音相关接口 ============
    
    /**
     * 文字转语音
     * @param {string} text - 文本内容
     * @param {number} conversationId - 会话ID
     */
    async textToSpeech(text, conversationId, settings = {}) {
        try {
            const response = await axios.post(`${this.baseUrl}/audio/speech`, {
                text: text,
                conversation_id: conversationId,
                model: settings.model,
                voice: settings.voice,
                response_format: settings.response_format
            });
            return response.data;
        } catch (error) {
            console.error('文字转语音失败:', error);
            if (window.ErrorHandler) {
                window.ErrorHandler.showError(error);
            }
            throw error;
        }
    }

    /**
     * 获取音频播放URL（完整路径）
     * @param {string} filename - 音频文件名
     */
    getAudioUrl(filename) {
        return `${this.baseUrl.replace('/api', '')}/api/audio/play/${filename}`;
    }


    // ============ 网络搜索接口 ============
    
    // 已移除：网络搜索接口

    // ============ 设置相关接口 ============
    
    /**
     * 获取所有设置
     */
    async getSettings() {
        try {
            const response = await axios.get(`${this.baseUrl}/settings`);
            return response.data;
        } catch (error) {
            console.error('获取设置失败:', error);
            if (window.ErrorHandler) {
                window.ErrorHandler.showError(error);
            }
            throw error;
        }
    }

    /**
     * 批量保存设置
     * @param {object} settings - 设置对象
     */
    async saveAllSettings(settings) {
        try {
            const response = await axios.post(`${this.baseUrl}/settings`, {
                settings: settings
            });
            return response.data;
        } catch (error) {
            console.error('保存设置失败:', error);
            if (window.ErrorHandler) {
                window.ErrorHandler.showError(error);
            }
            throw error;
        }
    }
}

// 导出 API 客户端实例
const apiClient = new ApiClient();

